package com.ruoyi.project.third;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @author 挺好的 2023年06月14日 下午 14:41
 */
//@Component
@Slf4j
public class AliMQConfig {



    @Bean
    public void getConsumer () {
        Properties properties = new Properties();
        // 您在控制台创建的Group ID。
        properties.put(PropertyKeyConst.GROUP_ID, "GID_ef923e43_zhejianglinggong");
        // AccessKey ID，阿里云身份验证标识。获取方式，请参见本文前提条件中的获取AccessKey。
        properties.put(PropertyKeyConst.AccessKey, "LTAI4GJhXnDLdJuEy2H5WC21");
        // AccessKey Secret，阿里云身份验证密钥。获取方式，请参见本文前提条件中的获取AccessKey。
        properties.put(PropertyKeyConst.SecretKey, "zTt6dTFc6gL1hpFQJSPqS7MBouOOiM");
        // 设置TCP协议接入点，进入控制台的实例详情页面的TCP协议客户端接入点区域查看。
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                "http://MQ_INST_1008227139678829_BcuN0Ins.mq-internet-access.mq-internet.aliyuncs.com:80"
        );
        // 集群订阅方式（默认）。
        // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
        // 广播订阅方式。
        // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);

        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe("ef923e43_zhejianglinggong",
                "JobComplete||Dialing || CallAnswered || CallFinished ||RecordingReady ", new MessageListener() {
                    //订阅多个Tag
                    @Override
                    public Action consume (Message message, ConsumeContext context) {
                        log.info("阿里云MQ回调信息打印：{}", JSONObject.toJSONString(message));
                        if (ObjectUtil.isNotEmpty(message)) {
                            try {
                                String decodeStr = new String(message.getBody(), "UTF-8");
                                if (ObjectUtil.isNotEmpty(decodeStr)) {
                                    JSONObject jsonObject = JSONObject.parseObject(decodeStr);
                                    if (!jsonObject.containsKey("contacts")) {
                                        return null;
                                    }
                                    JSONArray contacts = jsonObject.getJSONArray("contacts");
                                    if (ObjectUtil.isEmpty(contacts)) {
                                        return null;
                                    }
                                    String eventType = jsonObject.getString("eventType");
                                    Integer status;
                                    if ("JobComplete".equals(eventType)) {
                                        status = 4;
                                    } else if ("Dialing".equals(eventType)) {
                                        status = 5;
                                    } else if ("CallAnswered".equals(eventType)) {
                                        status = 6;
                                    } else if ("CallFinished".equals(eventType)) {
                                        status = 3;
                                    } else if ("RecordingReady".equals(eventType)) {
                                        status = 7;
                                    } else {
                                        status = 4;
                                    }
                                    for (int i = 0; i < contacts.size(); i++) {
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject job = contacts.getJSONObject(i);
                                        if (!job.containsKey("referenceId")) {
                                            return null;
                                        }
                                        String referenceId = job.getString("referenceId");
                                        // 得到 每个对象中的属性值
                                        System.out.println(job.get("name") + "=");
                                    }
                                    System.out.println("Receive: " + message);
                                    return Action.CommitMessage;
                                }
                            } catch (UnsupportedEncodingException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        return null;
                    }
                }
        );
       /* //订阅另外一个Topic，如需取消订阅该Topic，请删除该部分的订阅代码，重新启动消费端即可。
        consumer.subscribe("TopicTestMQ-Other", "*", new MessageListener() { //订阅全部Tag。
            @Override
            public Action consume (Message message, ConsumeContext context) {
                System.out.println("Receive: " + message);
                return Action.CommitMessage;
            }
        });*/
        consumer.start();
        System.out.println("Consumer Started");
    }
}
